package com.rongxun.api;

import com.rongxun.api.interceptor.TokenInterceptor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/5/18 14:07
 * 描述	     网络请求配置
 * <p>
 */

public class ApiProvider {
    private static final long     TIMEOUT = 15;
    private final        Retrofit mRetrofit;


    private static final Map<String, Object> serviceClassCaches = new ConcurrentHashMap<>();

    public ApiProvider(String pBaseUrl) {
        this(pBaseUrl, null);
    }

    public ApiProvider(String pBaseUrl, OkHttpClient pClient) {
        if (pClient == null) {
            pClient = createDefaultClient();
        }

        mRetrofit = new Retrofit.Builder()
                .baseUrl(pBaseUrl)
                .client(pClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private OkHttpClient createDefaultClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor())
                .addInterceptor(Api.sloggingInterceptor)
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .build();
    }


    public <T> T getService(Class<T> service) {

        T clazz = (T) serviceClassCaches.get(service.getName());

        if (clazz != null)
            return (T) clazz;

        synchronized (serviceClassCaches) {
            clazz = (T) serviceClassCaches.get(service.getName());
            if (clazz == null) {
                clazz = mRetrofit.create(service);
                serviceClassCaches.put(service.getName(), clazz);
            }
        }
        return clazz;
    }

}
